package show.me.the.money.config.reportSchema;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.dom4j.Element;

import show.me.the.money.config.reportSchema.define.ReportSchema;
import show.me.the.money.config.schema.SchemaItem;
import show.me.the.money.dictionary.Dictionary;
import show.me.the.money.dictionary.DictionaryItem;
import show.me.the.money.util.context.Context;


@SuppressWarnings("unchecked")
public class DictionaryReportDefine implements ReportDefine {
	private ReportSchema reportSchema;
	private List<SchemaItem> headers = new ArrayList<SchemaItem>();
	private int startRenderIndex;
	
	public void setDefineXML(Element define) {
		List<Element> els = define.selectNodes("headers/item");
		int  i = startRenderIndex;
		for(Element el : els){
			int index = Integer.parseInt(el.attributeValue("renderIndex",String.valueOf(i)));
			SchemaItem si = new SchemaItem(el,index);
			headers.add(si);
			i ++;
		}
	}
	
	public void addCondition(List topCnd) {
		
	}

	public List<SchemaItem> getHeaders(boolean group) {
		List<SchemaItem> ls = new ArrayList<SchemaItem>();
		for(SchemaItem i : headers){
			if(!group && i.isCodedValue()){
				continue;
			}
			ls.add(i);
		}
		return ls;
	}
	
	public int getHeaderCount() {
		return headers.size();
	}
	
	public void setStartRenderIndex(int start) {
		startRenderIndex = start;
	}

	public void runMutiMode(HashMap<String, HashMap> data, Context ctx) {
		SchemaItem si = headers.get(0);
		Dictionary dic = si.getRefDic();
		if(dic == null){
			return;
		}
		List<DictionaryItem> rs = dic.itemsList();
		
		for(DictionaryItem r : rs){
			HashMap o = null;
			String groupStr = r.getKey();
			if(data.containsKey(groupStr)){
				o = data.get(groupStr);
			}
			else{
				o = reportSchema.createEmptyRecord();
			}
			for(SchemaItem h : headers){
				String id = h.getId();
				if(h.isCodedValue()){
					o.put(id, r.getKey());
					o.put(id + "_text" , r.getText());
				}
				else{
					o.put(id, r.getProperty(id));
				}
			}
			data.put(groupStr,o);
		}
	}

	public List<HashMap> runSingleMode(Context ctx) {
		List<HashMap> data = new ArrayList<HashMap>();
		SchemaItem si = headers.get(0);
		Dictionary dic = si.getRefDic();
		if(dic == null){
			return data;
		}
		List<DictionaryItem> rs = dic.itemsList();
		for(DictionaryItem r : rs){
			HashMap o = new HashMap();
			
			for(SchemaItem h : headers){
				String id = h.getId();
				if(h.isCodedValue()){
					o.put(id, r.getKey());
					o.put(id + "_text" , r.getText());
				}
				else{
					o.put(id, r.getProperty(id));
				}
			}
			data.add(o);
		}
		return data;
	}

	public void setQueryArgs(List<SchemaItem> queryArgs) {
		// TODO Auto-generated method stub

	}

	public void setReportSchema(ReportSchema rs) {
		reportSchema = rs;
	}

}
